package ru.ifmo.network.skype;

import ru.ifmo.network.skype.audio.UserListHandler;
import ru.ifmo.network.skype.audio.VolumeController;
import ru.ifmo.network.skype.audio.receive.AudioDataReceiver;
import ru.ifmo.network.skype.audio.receive.Player;
import ru.ifmo.network.skype.network.MessageHandlerAdapter;
import ru.ifmo.network.skype.network.data.UserAddress;

import java.util.HashMap;
import java.util.Map;

/**
 * @author avhaliullin
 */
public class ReceiversGenerator extends MessageHandlerAdapter implements UserListHandler, VolumeController {
    private static final int MAX_QUEUE = 30;
    private final Player player;
    private Map<UserAddress, AudioDataReceiver> receivers = new HashMap<UserAddress, AudioDataReceiver>();

    public ReceiversGenerator(Player player) {
        this.player = player;
    }

    @Override
    public void moveUser(UserData user, Long group) {
    }

    public void newUser(UserData user) {
        AudioDataReceiver receiver = new AudioDataReceiver(MAX_QUEUE);
        receivers.put(user.getUserAddress(), receiver);
        player.addReceiver(receiver);
//        if (user.getUserAddress().getIpAddress().equals())
    }

    public void removeUser(UserData user) {
        AudioDataReceiver receiver = receivers.get(user.getUserAddress());
        player.removeReceiver(receiver);
    }

    public void handleAudio(UserAddress userAddress, long serialId, byte[] data) {
        AudioDataReceiver receiver = receivers.get(userAddress);
        if (receiver != null) {
            receiver.message(serialId, data);
        }

    }

    @Override
    public void setVolume(float volume) {
        player.setVolume(volume);
    }

    @Override
    public void setVolume(UserData userData, float volume) {
        if (userData != null) {
            AudioDataReceiver receiver = receivers.get(userData.getUserAddress());
            player.setVolume(receiver, volume);
        }
    }

    @Override
    public float getVolume() {
        return player.getVolume();
    }

    @Override
    public float getVolume(UserData userData) {
        if (receivers == null || player == null || userData == null) {
            return 1;
        }
        return player.getVolume(receivers.get(userData.getUserAddress()));
    }
}
